package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.MyEnum.NumberConstant;
import com.example.Utility.RedisUtils;
import com.example.Utility.Result;
import com.example.Utility.objIsNull;
import com.example.entity.UserMessage;
import com.example.mapper.UserMessageMapper;
import com.example.service.UsermessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
@RestController
@RequestMapping("/usermessage")
public class UserMessageController {

    @Resource
    private UsermessageService usermessageService;

    @Autowired
    private UserMessageMapper userInfoMapper;


    @Autowired
    private RedisUtils redisUtils;
    private Integer temp = 0;

    @PostMapping("/add")
    public boolean add(@RequestBody UserMessage userMessage) {
        Objects.requireNonNull(userMessage, "add user Message is fail");
        return usermessageService.save(userMessage);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody UserMessage userMessage) {
        LambdaQueryWrapper<UserMessage> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(UserMessage::getOpenid, userMessage.getOpenid());
        redisUtils.delete(userMessage.getOpenid() + "_date");
        return usermessageService.update(userMessage, updateWrapper);
    }

    @PostMapping("/getUser")
    public Result<UserMessage> get(@RequestBody UserMessage userMessage) {
        if (objIsNull.isNull(userMessage.getOpenid())) {
            return Result.fail(userMessage);
        }
        String redisKey = userMessage.getOpenid() + "_date";
        UserMessage userMsg = this.getMsgOne(userMessage.getOpenid());
        if (!redisUtils.haveKey(redisKey)) {
            redisUtils.redisAdd(userMessage.getOpenid(), userMsg.getState(), 1, TimeUnit.MINUTES);
            redisUtils.redisAdd(redisKey, userMsg, NumberConstant.ONE, TimeUnit.HOURS);
            if (userMsg.getState() != 1) {
                return Result.fail(userMessage);
            }
        } else {
            Integer integer = Integer.valueOf(redisUtils.getRedisDate(userMessage.getOpenid()));
            if (integer != 1) {
                return Result.fail(userMessage);
            }
        }
        return Result.succeed(redisUtils.getRedisObject(redisKey, UserMessage.class));
    }

    /**
     * 用户登录状态
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/state")
    public Boolean user_state(@RequestParam String openid,
                              @RequestParam Long state) {
        LambdaUpdateWrapper<UserMessage> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(UserMessage::getOpenid, openid);
        final UserMessage getone = usermessageService.getOne(updateWrapper);
        if (null == getone) {
            return false;
        }
        getone.setState(state);
        redisUtils.delete(openid);
        redisUtils.redisAdd(openid, state, NumberConstant.ONE, TimeUnit.DAYS);
        return usermessageService.updateById(getone);
    }

    @GetMapping("/getUserState")
    public Result getUserState(String openid) {
//        不等于空
        if (redisUtils.haveKey(openid)) {
            return Result.succeed(redisUtils.getRedisDate(openid));
        }
//        等于空
        UserMessage ume = this.getMsgOne(openid);
        if (null != ume) {
            redisUtils.redisAdd(openid, ume.getState(), 1, TimeUnit.HOURS);
            return Result.succeed(redisUtils.getRedisDate(openid));
        }
        return Result.fail("用户没有注册");
    }

    @GetMapping("/getPhone")
    public Object getPhone(String openid, String phone, String code) throws IOException {
        File file = new File("User");
        OutputStreamWriter os = null;
        FileReader fileInputStream = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileInputStream);
        while (bufferedReader.ready()) {
            bufferedReader.readLine().trim();
            if (bufferedReader.readLine().equals(openid)) {
                temp++;
            }
            if (temp == 3) {
                temp = temp - 3;
                return 1234;
            }
        }
        try {
            os = new OutputStreamWriter(new FileOutputStream(file, true));
            os.write("\r\n" + openid);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            os.close();
        }
        try {
            os = new OutputStreamWriter(new FileOutputStream(file, true));
            os.write("\r\n" + openid);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            os.close();
        }
        return 00;
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserMessageController that = (UserMessageController) o;
        return Objects.equals(usermessageService, that.usermessageService) && Objects.equals(userInfoMapper, that.userInfoMapper) && Objects.equals(temp, that.temp);
    }

    /**
     * 获取用户信息 唯一
     *
     * @param openid
     * @return
     */
    public UserMessage getMsgOne(String openid) {
        LambdaQueryWrapper<UserMessage> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UserMessage::getOpenid, openid);
        return usermessageService.getOne(wrapper);
    }
}
